<template>
  <div class="dashboard-container">
    <el-button class="add-btn" type="primary" size="default" @click="handleAddVillage">新增负责人</el-button>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column fixed type="index" label="序号" width="120" />
      <el-table-column prop="realname" label="负责人姓名" />
      <el-table-column prop="username" label="负责人账号" />
      <el-table-column prop="village['villageName']" label="负责村落" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-popconfirm title="确定删除?" @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <UserDialog v-if="dialogVisible" v-model:visible="dialogVisible" @refresh="getUserList" />
  </div>
</template>

<script lang="ts" name="User" setup>
import { deleteUser, userList } from '@/api/user'
import type { UserInfo } from '@/api/user.model'
import UserDialog from '@/components/dialogs/UserDialog.vue'
import useErrorMessage from '@/hooks/useErrorMessage'
import { ElMessage } from 'element-plus'

const tableData = ref<UserInfo[]>([])
const dialogVisible = ref<boolean>(false)

onMounted(() => {
  getUserList()
})

const getUserList = async () => {
  try {
    const { data } = await userList()
    tableData.value = data.data
  } catch (error) {
    useErrorMessage(error)
  }
}

const handleAddVillage = () => {
  dialogVisible.value = true
}

const handleDelete = async (row: UserInfo) => {
  try {
    await deleteUser(row.userId as number)
    ElMessage.success('删除成功')
    getUserList()
  } catch (error) {
    useErrorMessage(error)
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/variables.scss';

.dashboard-container {
  padding: 15px;
  color: $color-primary;
  .add-btn {
    float: right;
  }
}
</style>
